package com.cheney.weiboo.view;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.cheney.weiboo.R;
import com.cheney.weiboo.domain.Users;
import com.cheney.weiboo.service.UserService;
import com.cheney.weiboo.utils.AsyncImageLoader;
import com.cheney.weiboo.utils.RegexUtil;
import com.cheney.weiboo.utils.TextUtil;
import com.cheney.weiboo.utils.TimeUtil;
import com.cheney.weiboo.utils.WeiboContext;
import com.cheney.weiboo.utils.AsyncImageLoader.ImageCallback;
import com.mime.qweibo.examples.MyWeiboSync;
import com.mime.qweibo.examples.QWeiboType.PageFlag;

public class HomeTimeLineActivity extends ListActivity implements OnItemClickListener,OnItemLongClickListener{
	private Users currentUser ;
	private MyWeiboSync weibo;
	private UserService userService;
	private View topPanel;
	private TextView home_nick;
	private List<Users> userList;
	private ProgressDialog progressDialog;
	private Handler handler;
	private List<JSONObject> list;
	private static int PAGE_SIZE=20;//分页大小
	private int TOTAL_PAGE;//第几页
	private JSONArray array;
	private AsyncImageLoader imageLoader;
	private HomeAdapter adapter;
	private ListView listView;
	private ExecutorService executorService;
	private static int THREADPOOL_SIZE = 4;//线程池的大小
	private LinearLayout list_foot;
	private TextView tv_msg;
	private LinearLayout loading;
	private Button head_btn_right;
	private Button head_btn_left;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		Log.d("进入主页", "进入主页");
		setUpView();
		setUpListener();
		weibo = WeiboContext.getInstance();
		userService = new UserService(getApplicationContext());
		userList = userService.getUserList(false);
		//获得登录用户的信息
		SharedPreferences sp = getSharedPreferences("default_users",Context.MODE_PRIVATE);
		String nick = sp.getString("user_default_nick", "");
		Log.d("nick", "nick"+nick);
		if(nick!=null&&!"".equals(nick)){
			home_nick.setText(nick);
			currentUser = userService.getUserByName(nick, userList);
		}
		weibo.setAccessTokenKey(currentUser.getToken());
		weibo.setAccessTokenSecrect(currentUser.getTokenSecret());
		
		//创建进度条
		progressDialog = new ProgressDialog(this);
		progressDialog.setTitle("请稍后");
		progressDialog.setMessage("正在加载");
		progressDialog.setCancelable(true);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		
		handler = new GetHomeTimeLineHandler();
		
		executorService.submit(new GetHomeTimeLineThread());
		progressDialog.show();
		Log.d("没有阻塞", "没有阻塞");
		
	}
	
	public void setUpView(){
		topPanel = (View)findViewById(R.id.home_top);
		home_nick = (TextView)topPanel.findViewById(R.id.top_name);
		listView = getListView();
		executorService = Executors.newFixedThreadPool(THREADPOOL_SIZE);
		head_btn_right = (Button)topPanel.findViewById(R.id.top_btn_right);
		head_btn_left = (Button)topPanel.findViewById(R.id.top_btn_left);
		list = new ArrayList<JSONObject>();
		list_foot = (LinearLayout)LayoutInflater.from(HomeTimeLineActivity.this).inflate(R.layout.list_footer, null);
		tv_msg = (TextView)list_foot.findViewById(R.id.tv_msg);
		loading = (LinearLayout)list_foot.findViewById(R.id.loading);
		listView.addFooterView(list_foot);
	}

	public void setUpListener(){
		tv_msg.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//重新获取微博列表
				executorService.submit(new GetHomeTimeLineThread());
				tv_msg.setVisibility(View.GONE);
				loading.setVisibility(View.VISIBLE);
			}
		});
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		head_btn_right.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				//点击发布一条微博
				Intent intent = new Intent(HomeTimeLineActivity.this,AddWeiBoActivity.class);
				startActivity(intent);
			}
		});
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		//列表点击事件
		JSONObject obj = array.optJSONObject(position);
		Intent intent = new Intent(HomeTimeLineActivity.this,WeiBoDetailActivity.class);
		try {
			intent.putExtra("id", obj.getString("id"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		startActivity(intent);
	}
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		
		return false;
	}
	
	

	
	//获得内容
	public void refreshList(){
		String jsonStr = weibo.getHomeMsg(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect(), PageFlag.PageFlag_First, (TOTAL_PAGE+1)*PAGE_SIZE);
		try {
			JSONObject dataObj = new JSONObject(jsonStr).getJSONObject("data");
			array = dataObj.getJSONArray("info");
			Log.d("数据", dataObj.toString());
			if(array!=null&&array.length()>0){
				TOTAL_PAGE++;
				list.clear();
				int length = array.length();
				for(int i=0;i<length;i++){
					list.add(array.optJSONObject(i));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	class GetHomeTimeLineHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			Log.d("msg", msg.what+"");
			adapter = new HomeAdapter(getApplicationContext(),list);
			Log.d("PAGE_SIZE", TOTAL_PAGE+"");
			//如果不是第一次，那么当数据源发生改变以后，自动通知activity刷新list
			if(TOTAL_PAGE>1){
				adapter.notifyDataSetChanged();
			}
		    //如果是第一次，就直接设置为当前list的内容
			if(TOTAL_PAGE==1){
				listView.setAdapter(adapter);
			}
			listView.setSelection((TOTAL_PAGE-1)*PAGE_SIZE+1);
			progressDialog.dismiss();//关闭进度条
			loading.setVisibility(View.GONE);//隐藏最底下的进度条
			tv_msg.setVisibility(View.VISIBLE);//显示更多按钮
		}
		
	}
	
	class GetHomeTimeLineThread implements Runnable{
		@Override
		public void run() {
			//只是起了一个线程去处理请求数据
			refreshList();
			Message msg = handler.obtainMessage();//产生一个消息
			msg.what=1;
			//handler在收到消息以后，会调用handlerMessage方法处理ui事项
			handler.sendMessage(msg);
			
		}
		
	}
	
	
	class HomeAdapter extends BaseAdapter{
		private Context context;
		private LayoutInflater inflater;
		private List<JSONObject> jsonList;
		public HomeAdapter(Context context, List<JSONObject> jsonList){
			super();
			this.context = context;
			this.jsonList = jsonList;
			this.inflater = LayoutInflater.from(context);
			
		}
		@Override
		public int getCount() {
			return jsonList.size();
		}
		@Override
		public Object getItem(int position) {
			return jsonList.get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View view, ViewGroup viewGroup) {
			imageLoader = new AsyncImageLoader();
			JSONObject data = (JSONObject)list.get(position);
			JSONObject source = null;
			//减少对象的产生
			if(view==null){
			view = inflater.inflate(R.layout.home_item, null);
			}
			HomeViewHolder viewHolder = new HomeViewHolder();
			viewHolder.headicon = (ImageView)view.findViewById(R.id.home_headicon);
			viewHolder.home_nick = (TextView)view.findViewById(R.id.home_nick);
			viewHolder.home_vip = (ImageView)view.findViewById(R.id.home_vip);
			viewHolder.home_timestamp = (TextView)view.findViewById(R.id.home_timestamp);
			viewHolder.home_hasImage = (ImageView)view.findViewById(R.id.home_hasimage);
			viewHolder.home_oritext = (TextView)view.findViewById(R.id.home_oritext);
			viewHolder.home_source = (TextView)view.findViewById(R.id.home_source);
			if(data!=null){
				try {
					view.setTag(data.get("id"));//添加另一个属性，用于区分是哪一个
					viewHolder.home_nick.setText(data.getString("nick"));
					if(data.getInt("isvip")!=1){
						viewHolder.home_vip.setVisibility(View.GONE);
					}
					viewHolder.home_timestamp.setText(TimeUtil.converTime(Long.parseLong(data.getString("timestamp"))));
					//异步加载图片
					Drawable cachedImage = imageLoader.loadDrawable(data.getString("head")+"/100", viewHolder.headicon, new ImageCallback(){
						@Override
						public void imageLoaded(Drawable imageDrawable,
								ImageView imageView, String imageUrl) {
							imageView.setImageDrawable(imageDrawable);
						}
					});
					if(cachedImage!=null){
						viewHolder.headicon.setImageResource(R.drawable.icon);
					}else {
						viewHolder.headicon.setImageDrawable(cachedImage);
					}
					
					if(!"null".equals(data.getString("image"))){
						viewHolder.home_hasImage.setImageResource(R.drawable.hasimage);
					}
					//微博内容开始
					String orgText = data.getString("origtext");
					SpannableString spannable = new SpannableString(orgText);
					viewHolder.home_oritext.setText(spannable);
					//微博设置内容结束
					
					
					//处理引用 的内容
					if(!"null".equals(data.getString("source"))){
						source = data.getJSONObject("source");
					}
					if(source!=null){
						String home_source_text = null;
						boolean isVip = source.getInt("isvip")==1?true:false;
						if(isVip){
							home_source_text = "@"+source.getString("nick")+"======:"+source.getString("origtext");
						}else {
							home_source_text = "@"+source.getString("nick")+":"+source.getString("origtext");
						}
						SpannableString spannableSource = new SpannableString(home_source_text);
						spannableSource = TextUtil.decorateRefersInStr(spannableSource, RegexUtil.getStartAndEndIndex(home_source_text, Pattern.compile("@.*:")), getResources());
						spannableSource = TextUtil.decorateTopicInStr(spannableSource, RegexUtil.getStartAndEndIndex(home_source_text, Pattern.compile("#.*#")), getResources());
						spannableSource = TextUtil.decorateTopicInStr(spannableSource, RegexUtil.getStartAndEndIndex(home_source_text, Pattern.compile("^http://\\w+(\\.\\w+|)+(/\\w+)*(/\\w+\\.(\\w+|))?")), getResources());
						if(isVip){
							spannableSource = TextUtil.decorateVipInStr(spannableSource, RegexUtil.getStartAndEndIndex(home_source_text, Pattern.compile("======")), getResources());//替换为vip认证图片
						}
						viewHolder.home_source.setText(spannableSource);
						viewHolder.home_source.setBackgroundResource(R.drawable.home_source_bg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return view;
		}
	}
	//在产生列表的时候要减少对象的产生
	static class HomeViewHolder{
		ImageView headicon;
		TextView home_nick;
		ImageView home_vip;
		TextView home_timestamp;
		ImageView home_hasImage;
		TextView home_oritext;
		TextView home_source;
	}
	
	//创建操作菜单
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater mi = getMenuInflater();
		mi.inflate(R.menu.home_timeline_menu, menu);
		return true; 
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
	    	Toast t = Toast.makeText(getApplicationContext(), "back键按下", Toast.LENGTH_SHORT);
	    	t.show();
	    	Intent intent = new Intent(Intent.ACTION_MAIN);
	    	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    	intent.addCategory(Intent.CATEGORY_HOME);
	    	startActivity(intent);
	    	return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
}
